import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:LifeMusic/provider/userProvider.dart';

import 'package:LifeMusic/routers/application.dart';
import 'package:LifeMusic/utils/localStorage.dart';
import 'package:LifeMusic/api/userApi.dart';

class DrawerHeaderWidget extends StatefulWidget {
  @override
  _DrawerHeaderWidgetState createState() => _DrawerHeaderWidgetState();
}

class _DrawerHeaderWidgetState extends State<DrawerHeaderWidget> {
  Map<String,dynamic> famousWord={
    "hitokoto":'一蓑烟雨任平生,也无风雨也无晴',
    "from_who":'苏东坡'
  };

  Future getFamousWord() {
    return GetUserInfoAPi.famousWord();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getFamousWord().then((value) {
        print(value.runtimeType);
        setState(() {
          this.famousWord=new Map<String, dynamic>.from(value);
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(child: Consumer<UserState>(builder: (context, user, child) {
      return Stack(
        children: <Widget>[
          Positioned(
              top: -150,
              right: -150,
              child: Container(
                width: 300,
                height: 300,
                child: WaterRipplePage(),
              )),
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                alignment: AlignmentDirectional.bottomEnd,
                image: AssetImage('assets/images/mountain1.png'),
                fit: BoxFit.fitWidth,
              ),
            ),
            child: new ListView(
              children: <Widget>[
                new UserAccountsDrawerHeader(
                  //Material内置控件
                  accountName: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      RichText(
                        text: TextSpan(
                            style: DefaultTextStyle.of(context).style,
                            children: <InlineSpan>[
                              TextSpan(
                                  text: '你好，',
                                  style: TextStyle(color: Colors.red)),
                              TextSpan(
                                text: user.user.profile.nickname,
                                style: TextStyle(color: Colors.blue),
                              )
                            ]),
                      ),
                      FlatButton.icon(
                        onPressed: null,
                        icon: Icon(
                          Icons.brightness_high,
                          color: Colors.red,
                        ),
                        label: Container(
                          color: Color(0xFFEF5350),
                          child: Padding(
                            padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
                            child: Text(
                              "正式会员",
                              style:
                                  TextStyle(fontSize: 12, color: Colors.white),
                            ),
                          ),
                        ),
                      )
                    ],
                  ), //用户名
                  accountEmail: new Text(
                    '1163989452@qq.com',
                    style: TextStyle(color: Colors.blueGrey),
                  ), //用户邮箱
                  currentAccountPicture: new GestureDetector(
                    //用户头像
                    onTap: () {
                      Application.router.navigateTo(context, '/userCenter');
                    },
                    child: new CircleAvatar(
                      //圆形图标控件
                      backgroundImage: new NetworkImage(
                          user.user.profile.avatarUrl), //图片调取自网络
                    ),
                  ),
                  otherAccountsPictures: <Widget>[
                    //粉丝头像
                    new GestureDetector(
                      //手势探测器，可以识别各种手势，这里只用到了onTap
                      onTap: () {},
                      child: Icon(
                        Icons.line_style,
                        color: Colors.blue,
                      ),
                    ),
                    new GestureDetector(
                      onTap: () {},
                      child: Icon(
                        Icons.photo_camera,
                        color: Colors.blue,
                      ),
                    ),
                  ],
                  decoration: new BoxDecoration(
                    //用一个BoxDecoration装饰器提供背景图片
                    color: Color(0x00FFFFFF),
                    // image: new DecorationImage(
                    //     fit: BoxFit.fill,
                    //     image: new NetworkImage(
                    //         'http://img.netbian.com/file/2020/0904/9b933abf1608906132ef3d924910ae9e.jpg')
                    // ),
                  ),
                ),
                new ListTile(
                  //第一个功能项
                  title: new Text('首页'),
                  trailing: new Icon(Icons.home),
                ),
                new ListTile(
                  //第二个功能项
                  title: new Text('历史记录'),
                  trailing: new Icon(Icons.search),
                ),
                new ListTile(
                  //第二个功能项
                  title: new Text('下载管理'),
                  trailing: new Icon(Icons.save_alt),
                ),
                new ListTile(
                  //第二个功能项
                  title: new Text('我的收藏'),
                  trailing: new Icon(Icons.favorite),
                ),
                new ListTile(
                  //第二个功能项
                  title: new Text('稍后再看'),
                  trailing: new Icon(Icons.developer_board),
                ),
                new Divider(), //分割线控件
                new ListTile(
                  title: new Text('退出登录'),
                  trailing: new Icon(Icons.cancel),
                  onTap: () {
                    Navigator.of(context).pop();
                    Application.router
                        .navigateTo(context, '/loginPage', clearStack: true);
                    LocalStorage.remove('userInfo');
                  }, //点击后收起侧边栏
                ),
              ],
            ),
          ),
          Positioned(
              left: 10,
              bottom: 10,
              child: Stack(
                children: [
                  Container(
                      width: 300,
                      height: 120,
                      child: Text(
                        "${famousWord["hitokoto"]}",
                        style: TextStyle(fontSize: 22, fontFamily: 'xkfont'),
                      )),
                  Positioned(
                      bottom: 0,
                      right: 10,
                      child: Text(
                        "${famousWord["from_who"]==null?'':"作者："+famousWord["from_who"]}",
                        style: TextStyle(fontSize: 18, fontFamily: 'xkfont'),
                      ))
                ],
              )),
        ],
      );
    }));
  }
}

class WaterRipplePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Container(
              height: 300,
              width: 300,
              decoration: BoxDecoration(
                image: DecorationImage(
                  alignment: AlignmentDirectional.center,
                  image: AssetImage('assets/images/moon.png'),
                ),
              ),
              child: WaterRipple())),
    );
  }
}

class WaterRipple extends StatefulWidget {
  final int count;
  final Color color;

  const WaterRipple(
      {Key key, this.count = 3, this.color = const Color(0xFF90A4AE)})
      : super(key: key);

  @override
  _WaterRippleState createState() => _WaterRippleState();
}

class _WaterRippleState extends State<WaterRipple>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 2000))
          ..repeat();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(
          painter: WaterRipplePainter(_controller.value,
              count: widget.count, color: widget.color),
        );
      },
    );
  }
}

class WaterRipplePainter extends CustomPainter {
  final double progress;
  final int count;
  final Color color;

  Paint _paint = Paint()..style = PaintingStyle.fill;

  WaterRipplePainter(this.progress,
      {this.count = 3, this.color = const Color(0xFF0080ff)});

  @override
  void paint(Canvas canvas, Size size) {
    double radius = min(size.width / 2, size.height / 2);

    for (int i = count; i >= 0; i--) {
      final double opacity = (1.0 - ((i + progress) / (count + 1)));
      final Color _color = color.withOpacity(opacity);
      _paint..color = _color;

      double _radius = radius * ((i + progress) / (count + 1));

      canvas.drawCircle(
          Offset(size.width / 2, size.height / 2), _radius, _paint);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
